import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import ContentBox from 'components/contentBox'
import Filters from 'components/common/filters'
import CustomTable from 'components/common/table'
// import Authorized from 'components/common/authorized'
import { Form, message, Button, Modal, Input, Select, Popconfirm } from 'antd'
import { widgetType } from 'constants'
import PropTypes from 'prop-types'
import Style from './banner.css'

const formItemLayout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 16 }
}
const { TextArea } = Input
const { Option } = Select

const pushStatus = {
  0: '未发布',
  1: '已发布'
}

const msgType = {
  'SPECIFIC_EVENT': '官方特定事件',
  'COMMODITY_NEW': '艺术家作品上新'
}

class IndexForm extends Component {
  static propTypes = {
    form: PropTypes.object,
    getPushList: PropTypes.func,
    pushData: PropTypes.object,
    getAuthorList: PropTypes.func
  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {},
      editParams: {}
    }
    this.search = this.search.bind(this)
    this.reset = this.reset.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.onShowSizeChange = this.onShowSizeChange.bind(this)
    this.handleAdd = this.handleAdd.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
  }

  getFilterCols (category, author) {
    return [
      {
        label: '输入搜索',
        id: 'searchField',
        widget: widgetType.input,
        placeholder: '请输入推送编号/推送标题'
      }, {
        label: '推送类型',
        id: 'msgType',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '官方特定事件',
          value: 'SPECIFIC_EVENT'
        }, {
          text: '艺术家作品上新',
          value: 'COMMODITY_NEW'
        }]
      }, {
        label: '发布时间',
        id: 'publishTime',
        widget: widgetType.datePicker,
        placeholder: '请选择'
      }, {
        label: '发布人员',
        id: 'publishUserId',
        widget: widgetType.input,
        placeholder: '请输入'
      }, {
        label: false,
        span: 16,
        key: 'custom',
        widget: 'custom',
        formItemLayout: {},
        render: () => {
          return (
            <div className={Style['custom-buttons']}>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.search}>查询</Button>
              <Button style={{ marginRight: 10 }} onClick={this.reset}>重置</Button>
              <Button type='primary' onClick={this.handleAdd}>新建人工推送</Button>
            </div>
          )
        }
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '推送编号',
        dataIndex: 'code',
        key: 'code',
        width: 100
      },
      {
        title: '推送类型',
        dataIndex: 'msgType',
        key: 'msgType',
        width: 100,
        render: text => msgType[text]
      },
      {
        title: '推送标题',
        dataIndex: 'pushTitle',
        key: 'pushTitle',
        width: 100
      },
      {
        title: '发布状态',
        dataIndex: 'publishStatus',
        key: 'publishStatus',
        width: 100,
        render: text => pushStatus[text]
      },
      {
        title: '发布人员',
        dataIndex: 'publishUser',
        key: 'publishUser',
        width: 100,
        render: text => (text && text.userName) || '-'
      },
      {
        title: '发布时间',
        dataIndex: 'publishTime',
        key: 'publishTime',
        width: 100,
        render: text => text || '-'
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        render: (text, record) => {
          return <>
            <div>
              <a className={Style['a-btn']} onClick={() => this.handleShow(record)}>查看</a>
              {
                record.publishStatus === 0 && <a className={Style['a-btn']} onClick={() => this.handleEdit(record.id)}>编辑</a>
              }
            </div>
            {
              record.publishStatus === 0 && <div>
                <Popconfirm placement='top' title='确认是否发布' onConfirm={() => this.handlePush(record.id)}>
                  <a className={Style['a-btn']}>发布</a>
                </Popconfirm>

                <Popconfirm placement='top' title='确认是否删除' onConfirm={() => this.handleDel(record.id)}>
                  <a className={Style['a-btn']}>删除</a>
                </Popconfirm>
              </div>
            }
            {/* <Authorized auth='OPERATE:BANNER:DEL'>
              <Popconfirm placement='top' title='确认是否删除' onConfirm={() => this.handleDel(record.id)}>
                <a className={Style['a-btn']}>删除</a>
              </Popconfirm>
            </Authorized> */}
          </>
        },
        width: 140
      }
    ]
  }

  reset () {
    this.setState({
      pageNo: 1,
      pageSize: 20,
      params: {}
    })
    const { form } = this.props
    form.resetFields()
    this.props.getPushList({
      pageNo: 1,
      pageSize: 20,
      pushType: 2
    })
  }

  search () {
    const { pageSize, pageNo } = this.state
    let paramsData = {
      pageSize,
      pageNo,
      pushType: 2
    }

    // eslint-disable-next-line handle-callback-err
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (values.publishTime) {
        paramsData.publishTime = values.publishTime.format('YYYY-MM-DD HH:mm:ss')
      }
      paramsData.searchField = values.searchField
      paramsData.msgType = values.msgType
      paramsData.publishUserId = values.publishUserId
      this.setState({
        params: paramsData
      })
      this.props.getPushList(paramsData)
    })
  }

  handleAdd () {
    this.props.router.push(`/operation/add-push`)
  }

  handleEdit (id) {
    this.props.router.push(`/operation/edit-push/${id}`)
  }

  handleCancel () {
    this.setState({
      showModal: false
    })
  }

  handleShow (record) {
    this.props.getPushDetail({
      id: record.id
    })
  }

  onPageChange (pageNo, pageSize) {
    const { params } = this.state
    params.pageNo = pageNo
    params.pageSize = pageSize
    this.setState({
      pageNo
    })
    params.pushType = 2
    this.props.getPushList(params)
  }

  onShowSizeChange (current, pageSize) {
    this.setState({
      pageSize
    })
    const { params } = this.state
    params.pageNo = current
    params.pageSize = pageSize
    params.pushType = 2
    this.props.getPushList(params)
  }

  // 删除
  handleDel (id) {
    this.props.delTemplte({
      id
    })
  }

  handlePush (id) {
    this.props.publishTemplate({
      id
    })
  }

  componentDidMount () {
    const { pageSize, pageNo } = this.state
    this.props.getPushList({
      pageSize,
      pageNo,
      pushType: 2
    })
  }

  componentWillReceiveProps (nextProps) {
    if (!this.props.delRequest && nextProps.delRequest) {
      message.success('删除成功')
      this.search()
    }

    if (!this.props.publishRequest && nextProps.publishRequest) {
      message.success('发布成功')
      this.search()
    }

    if (!this.props.pushDetail && nextProps.pushDetail) {
      const userNameList = []
      nextProps.pushDetail.reveiveUserList && nextProps.pushDetail.reveiveUserList.forEach(element => {
        userNameList.push(element.userName)
      })
      nextProps.pushDetail.reveiveUserName = userNameList.join(',')
      this.setState({
        showModal: true,
        editParams: nextProps.pushDetail
      })
    }
  }

  render () {
    const { getFieldDecorator } = this.props.form

    const { pageNo, pageSize, showModal, editParams } = this.state
    const { form, pushData } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: pushData && pushData.total,
      onChange: this.onPageChange,
      pageSize,
      onShowSizeChange: this.onShowSizeChange
    }
    return (
      <>
        <ContentBox>
          <div className={Style['scenes-RecycleForm']}>
            <Filters
              cols={this.getFilterCols()}
              form={form}
              search={this.search}
              reset={this.reset}
              actions={false}
            >
              {/* <Button type='primary' onClick={this.handleAdd}>新建人工推送</Button> */}
            </Filters>
            <CustomTable
              loading={!pushData} columns={this.getTableCols()}
              dataSource={(pushData && pushData.list) || []}
              pagination={pagination} />
            <Modal
              title='详情'
              visible={showModal}
              width={600}
              destroyOnClose
              onCancel={this.handleCancel}
              onOk={this.handleCancel}
            >
              <Form {...formItemLayout}>
                <Form.Item label='消息标题'>
                  {getFieldDecorator('pushTitle', {
                    initialValue: editParams.pushTitle,
                    rules: [{ required: true, message: '请输入消息标题' }]
                  })(
                    <Input disabled placeholder='请输入' style={{ width: '400px' }} />
                  )}
                </Form.Item>
                <Form.Item label='消息内容'>
                  {getFieldDecorator('pushContent', {
                    initialValue: editParams.pushContent,
                    rules: [{ required: true, message: '请输入消息内容' }]
                  })(
                    <TextArea disabled placeholder='请输入' style={{ width: '400px' }} />
                  )}
                </Form.Item>
                <Form.Item label='消息类型'>
                  {getFieldDecorator('msgType', {
                    initialValue: editParams.msgType
                  })(
                    <Select disabled placeholder='请输入' onChange={this.msgTypeChange} style={{ width: '400px' }} >
                      <Option value='SPECIFIC_EVENT'>官方特定事件</Option>
                      <Option value='COMMODITY_NEW'>艺术家作品上新</Option>
                    </Select>)}
                </Form.Item>
                <Form.Item label='发布对象'>
                  {getFieldDecorator('remark', {
                    initialValue: editParams.reveiveUserName,
                    rules: [{ required: true, message: '请输选择布对象' }]
                  })(
                    <TextArea disabled placeholder='请输入' style={{ width: '400px' }} />
                  )}
                </Form.Item>
              </Form>
            </Modal>
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  pushData: state.operation.pushData,
  delRequest: state.operation.delRequest,
  publishRequest: state.operation.publishRequest,
  pushDetail: state.operation.pushDetail
})
const mapDispatch = dispatch => ({
  getPushList: dispatch.operation.getPushList,
  delTemplte: dispatch.operation.delTemplte,
  publishTemplate: dispatch.operation.publishTemplate,
  getPushDetail: dispatch.operation.getPushDetail
})

const Index = Form.create()(IndexForm)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Index)
)
